package com.dminvoicemanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.adapters.DM_ItemsList_Adapter;
import com.dminvoicemanager.printdoc.DM_Print_StockLoading;
import com.dminvoicemanager.printdoc.DM_Print_StockUnLoading;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class DM_Stock_UnLoading extends Activity {

	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// // Stock Loading
	// private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	// private String STOCK_LOAD_HEAD = "fLoadhed";
	// private String STOCK_LOAD_DETAIL = "fLoadDet";

	// // Stock Loading
	// private String STOCK_ORDER_HEAD = "FOrdHed";
	// private String STOCK_ORDER_DETAIL = "FOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	private SQLiteDatabase mydb;

	int SAVETAG = 0, UPDATETAG = 0, DELTAG = 0, countC = 44, CLEARTAG = 0,
			CANCELTAG = 0, SAVEDTAG = 0, DISPLAYSUMMARY = 0;
	int STOCKITEMSCHK = 0, chekVal = 0, CHKPHYSICAL = 0;
	String StlTransTypePrefix, stlAgentPrefixType, RepStLoadCode,
			tempRepStLoadSerialStr, printItemName, printItemsInCase,
			currentUserServerDB, UserAreaCode, UserDealCode, UserRouteCode,
			IntangFlg;
	EditText etdmstloadingmanuno, etdmstloadingdate, etstockloadingFLoc,
			etstockloadingToLoc, etdmstloadingremark, etdmstloadingitemname,
			etdmstloadingunits, etdmstloadingitemqoh, etdmstloadingitemcases,
			etdmstloadingitempieces, etdmstloadingitemprice,
			etdmstloadingcaseprice, myFilterItems;
	LinearLayout ListViewStLoadShowLocations, ListViewStLoadShowItems,
			ListViewStockLoadDetails, StockLoadActionButtons,
			dmstloadStockLoadingList;
	Button btnStockFromLocation, btnStockToLocation, btdmstLoadingselectitem,
			dmstockloadingback, dmstockloadingadd, dmstockloadingupdate,
			dmstockloadingdelete, etdmstloadingrefno, account_saveButton;
	String stLoaditemcode, LatestStLoadRefNo, currentFromLocationCode,
			currentStLoadTempRefCode, currentToLocationCode, CurrentLocCode,
			currentUserStLoad, currentUserPrefixLoad, stlrepusername,
			tempRepStLoadSerial, locationDetSummary, stLoadCurrentid,
			tempRepUnStLoadSerialCode, currentUserLocation, ItemPendingQtyStr,
			currentToLocQty, PrintcurrentUnitPriceAverage, strlastId,
			ItemQOHFromLoc, listsequence, deviceUser = "ANDROID",
			StockLoadingRef, stlAgentDealCode;
	int LocationTag, ButtonTag, LocationItemLoadRecId, stLoadLastSequence = 1;
	Double TotalLoadingValue = 0.0, case_price = 0.0, piece_price = 0.0,
			TotStLoadCaseItems = 0.0, TotStLoadPieces = 0.0, TotQtyVal = 0.0,
			LitemQOHVal = 0.0, ItemPendingQtyVal = 0.0, New_StockHand = 0.0,
			TotPiecesStLoad = 0.0, ItemsQOH = 0.0, CaseUnitAmountVal = 0.0,
			CurrentPirecesVal = 0.0;
	int ItemsCaseUnits = 0, ItemsCases = 0, ItemsPieces = 0, TotcasesItems = 0,
			TotalPiecesLoading = 0;
	int caseQtyValue = 0, casePiecesValue = 0, casePieQtyValue = 0;
	long lastId;
	AlertDialog StockLoadingAlert = null;
	final private static int DIALOG_SAVE_STOCK_LOADING = 1;
	final private static int DIALOG_CANCEL_STOCK_LOADING = 2;
	final private static int DIALOG_UNDO_STOCK_LOADING = 3;
	final private static int DIALOG_PRINT_STOCK_LOADING = 4;
	final private static int DIALOG_PRINT_NON_PHYSICAL = 5;
	private static final String TAG = null;

	private DM_ItemsList_Adapter dbHelper;
	private SimpleCursorAdapter dataAdapter;

	// Back to main screen from ListView
	public void btnStockItemsBack(View view) {
		ListViewStockLoadDetails.setVisibility(view.VISIBLE);
		StockLoadActionButtons.setVisibility(view.VISIBLE);
		ListViewStLoadShowItems.setVisibility(view.GONE);
		ListViewStLoadShowLocations.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);
	}

	public void btnStockLocationBack(View view) {
		ListViewStockLoadDetails.setVisibility(view.VISIBLE);
		StockLoadActionButtons.setVisibility(view.VISIBLE);
		ListViewStLoadShowItems.setVisibility(view.GONE);
		ListViewStLoadShowLocations.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);
	}

	public void ExitFromForm(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	public void AddStockLoadingDetails(View view) {
		Button des = (Button) view;
		currentStLoadTempRefCode = des.getText().toString();
		etdmstloadingrefno.setText(currentStLoadTempRefCode);
		ListViewStockLoadDetails.setVisibility(view.VISIBLE);
		StockLoadActionButtons.setVisibility(view.VISIBLE);
		ListViewStLoadShowItems.setVisibility(view.GONE);
		ListViewStLoadShowLocations.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);
		currentStLoadTempRefCode = currentStLoadTempRefCode.trim();
		DISPLAYSUMMARY = 202;
		disableControls();
		populateStockLoadSummary();
		// populateStockLoadSummary2();
		populateStockLoadList();
	}

	private void populateStockLoadSummary() {
		Log.v(TAG, "populateStockLoadSummary");
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor sumStLoad = null;

		try {
			sumStLoad = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN, null, null,
					null, null, null, null);
		} catch (Exception e1) {
		}

		if (sumStLoad != null) {
			if (sumStLoad.getCount() > 0) {
				while (sumStLoad.moveToNext()) {
					String tempRepStLoadRefNo = sumStLoad.getString(5);

					if (currentStLoadTempRefCode.equals(tempRepStLoadRefNo
							.trim())) {
						String fromLocName = sumStLoad.getString(10);
						String toLocName = sumStLoad.getString(11);
						String[] fromLocNameStr = fromLocName.split("/");
						String printFromLocName = fromLocNameStr[1];
						String[] toLocNameStr = toLocName.split("/");
						String printToLocName = toLocNameStr[1];

						etstockloadingFLoc.setText(printFromLocName);
						etstockloadingToLoc.setText(printToLocName);
					}

					Log.v(TAG, "SUM POSTIVE:" + tempRepStLoadRefNo + "/"
							+ currentStLoadTempRefCode);
				}
			} else {
				Log.v(TAG, "SUM NEGATIVE");
			}
		}

		Cursor sumHed = null;
		try {
			sumHed = mydb.query(STOCK_LOAD_HEADUN, null, null, null, null,
					null, null);
		} catch (Exception e1) {
		}

		if (sumHed != null) {
			if (sumHed.getCount() > 0) {
				while (sumHed.moveToNext()) {
					String RefNo = sumHed.getString(1);
					if (currentStLoadTempRefCode.equals(RefNo.trim())) {
						String TxnDate = sumHed.getString(2);
						String ManuRef = sumHed.getString(3);
						String Remarks = sumHed.getString(5);
						etdmstloadingmanuno.setText(ManuRef.trim());
						etdmstloadingdate.setText(TxnDate.trim());
						etdmstloadingremark.setText(Remarks.trim());
						Log.v(TAG, "DET POSTIVE:" + RefNo + "/"
								+ currentStLoadTempRefCode + TxnDate + ManuRef
								+ Remarks);
					}

				}
			} else {
				Log.v(TAG, "SUM NEGATIVE");
			}
		}
	}

	private void disableControls() {
		// TODO Auto-generated method stub
		account_saveButton.setEnabled(false);
		btnStockFromLocation.setEnabled(false);
		btnStockToLocation.setEnabled(false);
		btdmstLoadingselectitem.setEnabled(false);
		dmstockloadingadd.setEnabled(false);
		dmstockloadingdelete.setEnabled(false);
		dmstockloadingupdate.setEnabled(false);
		etdmstloadingitemcases.setEnabled(false);
		etdmstloadingitempieces.setEnabled(false);
	}

	// ---------Set Location Details in to Main details View
	// Pannel---------------
	public void AddLocationDetails(View view) {

		Button des = (Button) view;
		locationDetSummary = des.getText().toString();
		String[] Locationsdetail = locationDetSummary.split("/");
		CurrentLocCode = Locationsdetail[0]; // invitemskucode
		String LocName = Locationsdetail[1]; // invitemname
		String LoctCode = Locationsdetail[2]; // invitemsincase

		// etstockloadingFLoc, etstockloadingToLoc ,LocationTag (From=1 ,To=2)

		// Stock Loading From Location
		if (LocationTag == 100) {
			currentFromLocationCode = CurrentLocCode;
			if (currentFromLocationCode.equals(currentToLocationCode)) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Stock_UnLoading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVALID LOCATION");
				// Setting Dialog Message
				alertDialog.setMessage("Please Select Another Location");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
			} else {
				upDateStockLocation();
				etstockloadingFLoc.setText(LocName);
				StockLoadActionButtons.setVisibility(view.VISIBLE);
				ListViewStockLoadDetails.setVisibility(view.VISIBLE);
				ListViewStLoadShowItems.setVisibility(view.GONE);
				ListViewStLoadShowLocations.setVisibility(view.GONE);
				dmstloadStockLoadingList.setVisibility(view.GONE);
			}

		}
		// Stock Loading To Location
		else if (LocationTag == 200) {
			currentToLocationCode = CurrentLocCode;
			if (currentToLocationCode.equals(currentFromLocationCode)) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Stock_UnLoading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVALID LOCATION");
				// Setting Dialog Message
				alertDialog.setMessage("Please Select Another Location");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			} else {
				upDateStockLocation();
				etstockloadingToLoc.setText(LocName);
				StockLoadActionButtons.setVisibility(view.VISIBLE);
				ListViewStockLoadDetails.setVisibility(view.VISIBLE);
				ListViewStLoadShowItems.setVisibility(view.GONE);
				ListViewStLoadShowLocations.setVisibility(view.GONE);
				dmstloadStockLoadingList.setVisibility(view.GONE);
			}
		}

	}

	// Update Location in to summary table
	private void upDateStockLocation() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor selectLastinvrecLoc = null;
		try {
			selectLastinvrecLoc = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN,
					null, "stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectLastinvrecLoc != null) {
			if (selectLastinvrecLoc.getCount() > 0) {
				while (selectLastinvrecLoc.moveToNext()) {
					ContentValues valueupdateLocation = new ContentValues();
					stlrepusername = selectLastinvrecLoc.getString(1);
					String currentStLoadCodeLoc = selectLastinvrecLoc
							.getString(5);

					if (LocationTag == 100) {
						valueupdateLocation.put("fromLocName",
								locationDetSummary);// Update
						// From
						// Location
					} else if (LocationTag == 200) {
						valueupdateLocation
								.put("toLocName", locationDetSummary);// Update
						// To
						// Location
					}
					mydb.update(TEMP_STOCK_LOADING_SUMMARYUN,
							valueupdateLocation, "tempRepStLoadRefNo ='"
									+ currentStLoadCodeLoc + "'", null);
				}
			}
		}
		selectLastinvrecLoc.close();
		mydb.close();
	}

	// ---------Set Items Details in to Main details View Pannel------
	public void AddLocationItemsDetails(View view) {

		Button des = (Button) view;
		String ItemsRawResult = des.getText().toString();
		stLoaditemcode = ItemsRawResult.trim();
		getItemDetails();
		CheckItemWithStock();
		resetCasePieces();

		if (chekVal == 0) {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor setStockLocation = null;
			try {
				setStockLocation = mydb.query(STOCK_LOAD_DETAILUN, null,
						"RefNo='" + currentStLoadTempRefCode + "'", null, null,
						null, null);
			} catch (Exception e) {
			}
			try {
				if (setStockLocation != null) {
					if (setStockLocation.getCount() > 0) {
						while (setStockLocation.moveToNext()) {
							String stLocItemCode = setStockLocation
									.getString(6);

							if (stLocItemCode.equals(stLoaditemcode)) {
								chekVal = 12;

							} else {

								etdmstloadingunits.setText(printItemsInCase);
								etdmstloadingitemname.setText(printItemName);
								ListViewStockLoadDetails
										.setVisibility(view.VISIBLE);
								StockLoadActionButtons
										.setVisibility(view.VISIBLE);
								ListViewStLoadShowItems
										.setVisibility(view.GONE);
								ListViewStLoadShowLocations
										.setVisibility(view.GONE);
								dmstloadStockLoadingList
										.setVisibility(view.GONE);
								setQtyOnHandPrice();

							}
						}
						if (chekVal == 12) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_Stock_UnLoading.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("INVALID ITEM");
							// Setting Dialog Message
							alertDialog
									.setMessage("Selected Item Unload Completed");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											chekVal = 0;
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
					} else {

						etdmstloadingunits.setText(printItemsInCase);
						etdmstloadingitemname.setText(printItemName);
						ListViewStockLoadDetails.setVisibility(view.VISIBLE);
						StockLoadActionButtons.setVisibility(view.VISIBLE);
						ListViewStLoadShowItems.setVisibility(view.GONE);
						ListViewStLoadShowLocations.setVisibility(view.GONE);
						setQtyOnHandPrice();

					}
				} else {

					etdmstloadingunits.setText(printItemsInCase);
					etdmstloadingitemname.setText(printItemName);
					ListViewStockLoadDetails.setVisibility(view.VISIBLE);
					StockLoadActionButtons.setVisibility(view.VISIBLE);
					ListViewStLoadShowItems.setVisibility(view.GONE);
					ListViewStLoadShowLocations.setVisibility(view.GONE);
					setQtyOnHandPrice();

				}
			} catch (Exception e) {
			}
			setStockLocation.close();
			mydb.close();
		}
	};

	private void getItemDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curGetItemsDetails = null;
		try {
			curGetItemsDetails = mydb.query(ITEMS, null, "ItemCode='"
					+ stLoaditemcode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curGetItemsDetails != null) {
			if (curGetItemsDetails.getCount() > 0) {
				while (curGetItemsDetails.moveToNext()) {
					String itemskucode = curGetItemsDetails.getString(1);
					String itemcode = curGetItemsDetails.getString(2);
					printItemName = curGetItemsDetails.getString(4);
					printItemsInCase = curGetItemsDetails.getString(28);

				}
			}
		}
		curGetItemsDetails.close();
		mydb.close();
	}

	private void resetCasePieces() {
		// TODO Auto-generated method stub
		etdmstloadingitemcases.setText("");
		etdmstloadingitempieces.setText("");
	}

	private void CheckItemWithStock() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor setQtyonHand = null;
		try {
			setQtyonHand = mydb.query(ITEM_LOC_DETAILS, null, "LocCode='"
					+ currentFromLocationCode + "' AND ItemCode='"
					+ stLoaditemcode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		try {
			if (setQtyonHand != null) {
				if (setQtyonHand.getCount() > 0) {
					chekVal = 0;
				} else {
					chekVal = 34;
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("ITEM NOT AVAILABLE");
					// Setting Dialog Message
					alertDialog
							.setMessage("No Items For Stock Unloading.Select Another Item");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									chekVal = 34;
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			}
		} catch (Exception e) {
		}

	}

	// Set Items stock Quantity in From Location
	private void setQtyOnHandPrice() {
		// TODO Auto-generated method stub =currentFromLocationCode
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor setQtyonHand = null;
		try {
			setQtyonHand = mydb.query(ITEM_LOC_DETAILS, null, "LocCode='"
					+ currentFromLocationCode + "' AND ItemCode='"
					+ stLoaditemcode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		try {
			if (setQtyonHand != null) {
				if (setQtyonHand.getCount() > 0) {
					while (setQtyonHand.moveToNext()) {
						String locCode = setQtyonHand.getString(1);
						String ItemCode = setQtyonHand.getString(2);
						String qtyOnHand = setQtyonHand.getString(3);

						etdmstloadingitemqoh.setText(qtyOnHand);
					}
				}

			}
		} catch (Exception e) {

		}
		setQtyonHand.close();
		mydb.close();
		// ==========================Set Price=================================
		stLoaditemcode.trim();
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		String[] cols = { "ItemCode" };
		Cursor chkItemPrice = null;

		try {
			String query = "SELECT ITP.ItemCode,ITP.PrilCode, ITP.Price, ITM.AvgPrice from fItemPri ITP, fItems ITM Where ITP.ItemCode = ITM.ItemCode order by ITP.ItemCode";
			chkItemPrice = mydb.rawQuery(query, null);
		} catch (Exception e1) {
		}
		if (chkItemPrice != null) {
			if (chkItemPrice.getCount() > 0) {

				while (chkItemPrice.moveToNext()) {
					String itemsUnitsPerCase = etdmstloadingunits.getText()
							.toString();
					double currentUnitQty = Double
							.parseDouble(itemsUnitsPerCase);
					String itemcodep = chkItemPrice.getString(0);
					String itempricatcode = chkItemPrice.getString(1);
					String pricecat = itempricatcode.substring(0, 1);
					String itemprice = chkItemPrice.getString(2);
					String caseAvgPrice = chkItemPrice.getString(3);
					Log.v(TAG, "caseitemprice:" + itemprice);
					Log.v(TAG, "caseAvgPrice:" + caseAvgPrice);
					// cost price = average case price
					double currentUnitPriceOri = Double
							.parseDouble(caseAvgPrice);
					currentUnitPriceOri = Math.round(currentUnitPriceOri * 100) / 100.0d;
					String PrintcurrentUnitPriceRegular = Double
							.toString(currentUnitPriceOri);

					double currentUnitPrice = Double.parseDouble(caseAvgPrice);
					// currentUnitPrice = Math.round(currentUnitPrice * 100) /
					// 100.0d;
					String PrintcurrentUnitPriceAvg = Double
							.toString(currentUnitPrice);
					double currentItemsPrice = currentUnitPrice
							/ currentUnitQty;
					// currentItemsPrice = Math.round(currentItemsPrice * 100) /
					// 100.0d;
					String PrintcurrentItemsPrice = Double
							.toString(currentItemsPrice);
					itemcodep.trim();

					if (itemcodep.equals(stLoaditemcode)) {

						if (itempricatcode.equals("WSP001")) {
							PrintcurrentUnitPriceAverage = PrintcurrentUnitPriceRegular
									.trim();
							etdmstloadingitemprice
									.setText(PrintcurrentItemsPrice);
							etdmstloadingcaseprice
									.setText(PrintcurrentUnitPriceAvg);
						} else {

						}
						PrintcurrentUnitPriceAverage = PrintcurrentUnitPriceRegular
								.trim();
						etdmstloadingitemprice.setText(PrintcurrentItemsPrice);
						etdmstloadingcaseprice
								.setText(PrintcurrentUnitPriceAvg);
					} else {

					}
				}
			}
			chkItemPrice.close();
		} else {
			Toast.makeText(getApplicationContext(), "ItemNot Found", 1).show();
		}
		chkItemPrice.close();
		mydb.close();
	}

	// View Loading Item from the List (Update /Delete)
	public void ShowItemsDetails(View view) {
		Button desstl = (Button) view;
		String ItemsRawResultStl = desstl.getText().toString();
		String[] ItemsRawResultDis = ItemsRawResultStl.split("/");
		String recitemid = ItemsRawResultDis[0]; // invitemskucode
		LocationItemLoadRecId = Integer.parseInt(recitemid);
		stLoaditemcode = ItemsRawResultDis[1]; // ItemCode
		String PiceQty = ItemsRawResultDis[2]; // PiceQty
		String CaseQty = ItemsRawResultDis[3]; // CaseQty
		String ItemName = ItemsRawResultDis[4]; // ItemName
		String ItemQOH = ItemsRawResultDis[5]; // ItemQOH
		String CaseUnits = ItemsRawResultDis[6]; // CaseUnits
		etdmstloadingitemname.setText(ItemName);
		etdmstloadingunits.setText(CaseUnits);
		etdmstloadingitemqoh.setText(ItemQOH);
		etdmstloadingitemcases.setText(CaseQty);
		etdmstloadingitempieces.setText(PiceQty);
		dmstockloadingadd.setEnabled(false);
		dmstockloadingdelete.setEnabled(true);
		dmstockloadingupdate.setEnabled(true);
		/*
		 * Toast.makeText(getApplicationContext(), "LocationItemLoadRecId**:" +
		 * LocationItemLoadRecId, 1).show();
		 */
	}

	// ----------------------------------------------------------------------------------
	// Main Stock Loading Button Actions
	// Save Stock details and invoice header details to activate invoice
	public void btnSaveLoding(View view) {
		checkItemsAvailable();
		if (STOCKITEMSCHK == 101) {
			try {
				showDialog(DIALOG_PRINT_NON_PHYSICAL);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else if (STOCKITEMSCHK == 102) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Stock_UnLoading.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("ITEMS LOAD");
			// Setting Dialog Message
			alertDialog.setMessage("No Items For Stock Unloading");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	public void btnBtnPhysical(View view) {
		CHKPHYSICAL = 200;
		ButtonTag = 2;
		IntangFlg = "0";
		StockLoadingAlert.dismiss();
		SaveMainStockLoading();

	}

	public void btnBtnNonPhysical(View view) {
		CHKPHYSICAL = 0;
		ButtonTag = 2;
		IntangFlg = "1";
		UpdateUnloadHedAndDet();
		StockLoadingAlert.dismiss();
		SaveMainStockLoading();
	}

	private void UpdateUnloadHedAndDet() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor updateNonPhysical = null;
		try {
			updateNonPhysical = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN, null,
					"stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (updateNonPhysical != null) {
			if (updateNonPhysical.getCount() > 0) {
				while (updateNonPhysical.moveToNext()) {

					String RefNo = updateNonPhysical.getString(5);

					try {
						ContentValues updateUnloadHed = new ContentValues();
						updateUnloadHed.put("IntangFlg", "1");
						mydb.update(STOCK_LOAD_HEADUN, updateUnloadHed,
								"RefNo ='" + RefNo + "'", null);
					} catch (Exception e) {
					}

					try {
						ContentValues updateUnloadDet = new ContentValues();
						updateUnloadDet.put("IntangFlg", "1");
						mydb.update(STOCK_LOAD_DETAILUN, updateUnloadDet,
								"RefNo ='" + RefNo + "'", null);
					} catch (Exception e) {
					}
				}
			}
		}
		updateNonPhysical.close();
		mydb.close();
	}

	private void checkItemsAvailable() {
		// TODO Auto-generated method stub
		String currentStLoadCodeRef = etdmstloadingrefno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkItems = null;
		try {
			curChkItems = mydb.query(STOCK_LOAD_DETAILUN, null, "RefNo='"
					+ currentStLoadCodeRef + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curChkItems != null) {
			if (curChkItems.getCount() > 0) {
				STOCKITEMSCHK = 101;
			} else {
				STOCKITEMSCHK = 102;
			}
		}
		curChkItems.close();
		mydb.close();
	}

	// Update and create new Stock Loading
	private void SaveMainStockLoading() {
		// TODO Auto-generated method stub
		int DELTAG = 0;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStockLoadingMain = null;
		try {
			saveStockLoadingMain = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN,
					null, "stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (saveStockLoadingMain != null) {
			if (saveStockLoadingMain.getCount() > 0) {
				while (saveStockLoadingMain.moveToNext()) {
					ContentValues valueupdateStLoadState = new ContentValues();
					stLoadCurrentid = saveStockLoadingMain.getString(0);
					tempRepStLoadSerialStr = saveStockLoadingMain.getString(4);
					valueupdateStLoadState.put("stLoadActive", "2");
					mydb.update(TEMP_STOCK_LOADING_SUMMARYUN,
							valueupdateStLoadState, "temprepStLoad_id ='"
									+ stLoadCurrentid + "'", null);
					saveNewStockLoadingRec();

					if (ButtonTag == 2) {
						try {
							showDialog(DIALOG_SAVE_STOCK_LOADING);
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

				}

			}
		}
		saveStockLoadingMain.close();
		mydb.close();

	}

	private void saveNewStockLoadingRec() {
		// TODO Auto-generated method stub
		int tempRepStLoadSerialId = Integer.parseInt(tempRepStLoadSerialStr);
		int newStLoadSerialId = tempRepStLoadSerialId + 1;
		tempRepStLoadSerialStr = Integer.toString(newStLoadSerialId);
		RepStLoadCode = StlTransTypePrefix.trim() + stlAgentPrefixType.trim()
				+ currentUserPrefixLoad;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues saveStockLoadSummary = new ContentValues();
			saveStockLoadSummary.put("stlrepusername", currentUserStLoad);
			saveStockLoadSummary.put("stlrepprefix", currentUserPrefixLoad);
			saveStockLoadSummary.put("tempRepStLoadCode", RepStLoadCode);
			saveStockLoadSummary.put("tempRepStLoadSerial",
					tempRepStLoadSerialStr);

			try {
				if (tempRepStLoadSerialStr.length() == 1) {
					String newInvNumberStr = "00000" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 2) {
					String newInvNumberStr = "0000" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 3) {
					String newInvNumberStr = "000" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 4) {
					String newInvNumberStr = "00" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 5) {
					String newInvNumberStr = "0" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {

			}
			saveStockLoadSummary.put("tempRepStLoadRefNo",
					currentStLoadTempRefCode);
			saveStockLoadSummary.put("stLoadComplete", "0");
			saveStockLoadSummary.put("stLoadActive", "9");
			saveStockLoadSummary.put("stLoadActiveValue", "0");
			saveStockLoadSummary.put("stLoadstartDate", getCurrentTimeString());
			saveStockLoadSummary.put("fromLocName", "");
			saveStockLoadSummary.put("toLocName", "");
			mydb.insert(TEMP_STOCK_LOADING_SUMMARYUN, null,
					saveStockLoadSummary);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Record Not Insert..",
					Toast.LENGTH_SHORT).show();
		}
		updateFcompanyBranch();
		if (CHKPHYSICAL == 200) {
			updateMainStocks();
			Log.v(TAG, "Non Physical Unloading No");
		} else {
			Log.v(TAG, "Non Physical Unloading Yes");
			clearFieldsStLoad();
			SAVETAG = 0;
			DELTAG = 0;
			CHKPHYSICAL = 0;
		}

		mydb.close();
	}

	private void updateFcompanyBranch() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='STRUN' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", tempRepStLoadSerialStr);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}

	}

	// +++++++++ xxxdela++++++++++++++
	private void updateMainStocks() {
		// TODO Auto-generated method stub
		String currentStLoadCodeRef = etdmstloadingrefno.getText().toString();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String currentRefStr = currentStLoadTempRefCode.trim();
		Cursor stockLoaddetQty = null;
		Cursor saveStockQuantityMain = null;
		try {
			stockLoaddetQty = mydb.query(STOCK_LOAD_DETAILUN, null, "RefNo='"
					+ currentStLoadCodeRef + "'", null, null, null, null);

		} catch (Exception e) {
		}
		if (stockLoaddetQty != null) {
			if (stockLoaddetQty.getCount() > 0) {
				while (stockLoaddetQty.moveToNext()) {
					String RefNo = stockLoaddetQty.getString(1);
					String LocCode = stockLoaddetQty.getString(3);
					String ItemCode = stockLoaddetQty.getString(6);
					String Qty = stockLoaddetQty.getString(9);
					String RecordStatus = stockLoaddetQty.getString(13);
					String LitemQOH = stockLoaddetQty.getString(15);

					TotQtyVal = Double.parseDouble(Qty);
					LitemQOHVal = Double.parseDouble(LitemQOH);

					if (RecordStatus.equals("99")) {
						ItemPendingQtyVal = LitemQOHVal + TotQtyVal;
						ItemPendingQtyStr = Double.toString(ItemPendingQtyVal);
					} else if (RecordStatus.equals("88")) {
						ItemPendingQtyVal = LitemQOHVal + TotQtyVal;
						ItemPendingQtyStr = Double.toString(ItemPendingQtyVal);
					}
					// ==================================================================
					/*
					 * Toast.makeText(getApplicationContext(), "PendingQTY|" +
					 * ItemPendingQtyStr, Toast.LENGTH_SHORT).show();
					 */

					String[] selectstate = { "LocCode", "ItemCode" };
					try {
						saveStockQuantityMain = mydb.query(ITEM_LOC_DETAILS,
								null, "LocCode='" + LocCode
										+ "' AND ItemCode='" + ItemCode + "'",
								null, null, null, null);

					} catch (Exception e) {
					}
					if (saveStockQuantityMain != null) {
						if (saveStockQuantityMain.getCount() > 0) {
							while (saveStockQuantityMain.moveToNext()) {
								ContentValues valueupdateMainQty = new ContentValues();
								String LocCodechk = saveStockQuantityMain
										.getString(1);
								String ItemCodechk = saveStockQuantityMain
										.getString(2);
								String LocQtychkr = saveStockQuantityMain
										.getString(3);
								String RecordIdhkr = saveStockQuantityMain
										.getString(4);
								valueupdateMainQty
										.put("QOH", ItemPendingQtyStr);
								valueupdateMainQty.put("syncRec", "1");
								mydb.update(ITEM_LOC_DETAILS,
										valueupdateMainQty, "RecordId ='"
												+ RecordIdhkr + "'", null);
							}
						} else {
							Toast.makeText(getApplicationContext(),
									"*****NO LOC ITEM*******",
									Toast.LENGTH_SHORT).show();
						}
					}
				}
			} else {
				Toast.makeText(getApplicationContext(), "***No Records***",
						Toast.LENGTH_SHORT).show();
			}
		}
		clearFieldsStLoad();
		SAVETAG = 0;
		DELTAG = 0;
		saveStockQuantityMain.close();
		stockLoaddetQty.close();
		mydb.close();

	}

	public void btnSaveInvoiceAccept(View view) {
		if (etdmstloadingrefno.length() != 0) {

			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			StockLoadingAlert.dismiss();
			finish();
			return;

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Stock_UnLoading.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("STOCK UNLOAD ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Stock Unloading Not Found");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// -------------Cancel Stock Loading-------------------------
	public void btnCanclloading(View view) {
		checkStockLoadSaved();
		if (CANCELTAG == 45) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Stock_UnLoading.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("STOCK UNLOADING NOT SAVED");
			// Setting Dialog Message
			alertDialog
					.setMessage("Selected Stock Unload Not Saved.Select Valid Stock Unload To Cancel");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CANCELTAG = 0;
					alertDialog.dismiss();
				}
			});
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			checkItemsAvailable();
			if (STOCKITEMSCHK == 101) {
				if (etdmstloadingrefno.length() != 0) {
					try {
						ButtonTag = 3;
						showDialog(DIALOG_CANCEL_STOCK_LOADING);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT STOCK UNLOADING");
					// Setting Dialog Message
					alertDialog.setMessage("Select Valid Stock Unloading");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			} else if (STOCKITEMSCHK == 102) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Stock_UnLoading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("ITEMS UNLOAD");
				// Setting Dialog Message
				alertDialog.setMessage("No Items For Stock Unloading");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}

	}

	private void checkStockLoadSaved() {
		// TODO Auto-generated method stub
		String CurrentStLoadRefNo = etdmstloadingrefno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentStLoadRefCur = null;
		try {
			CurrentStLoadRefCur = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN,
					null, "stlrepusername='" + currentUserStLoad
							+ "' AND tempRepStLoadRefNo='" + CurrentStLoadRefNo
							+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (CurrentStLoadRefCur != null) {
			if (CurrentStLoadRefCur.getCount() > 0) {
				while (CurrentStLoadRefCur.moveToNext()) {
					String stLoadActive = CurrentStLoadRefCur.getString(7);
					if (stLoadActive.equals("9")) {
						CANCELTAG = 45;
					} else if (stLoadActive.equals("2")) {
						SAVEDTAG = 66;
					}

				}
			}
		}
		CurrentStLoadRefCur.close();
		mydb.close();
	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		StockLoadingAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		cancelNewStockLoadingRec();
		Intent myIntent = new Intent(view.getContext(),
				DM_Stock_UnLoading.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	private void cancelNewStockLoadingRec() {
		// TODO Auto-generated method stub
		String CurrentStLoadRefNo = etdmstloadingrefno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStockLoadingMain = null;
		try {
			saveStockLoadingMain = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN,
					null, "stlrepusername='" + currentUserStLoad
							+ "' AND tempRepStLoadRefNo='" + CurrentStLoadRefNo
							+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (saveStockLoadingMain != null) {
			if (saveStockLoadingMain.getCount() > 0) {
				while (saveStockLoadingMain.moveToNext()) {
					ContentValues valueupdateStLoadState = new ContentValues();
					stLoadCurrentid = saveStockLoadingMain.getString(0);
					tempRepStLoadSerialStr = saveStockLoadingMain.getString(4);
					valueupdateStLoadState.put("stLoadActive", "5");
					mydb.update(TEMP_STOCK_LOADING_SUMMARYUN,
							valueupdateStLoadState, "temprepStLoad_id ='"
									+ stLoadCurrentid + "'", null);
					// saveNewStockLoadingRec();
				}

			}
		}
		saveStockLoadingMain.close();
		mydb.close();

	}

	// -----------------------------------------------------------------------------
	// ==============Undo Invoice====================
	public void btnUndoLoading(View view) {
		if (etdmstloadingrefno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_STOCK_LOADING);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Stock_UnLoading.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT STOCK UNLOADING");
			// Setting Dialog Message
			alertDialog.setMessage("Select Valid Stock Unloading");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		StockLoadingAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		// updateStLoadUndoState();
		CLEARTAG = 22;
		clearFieldsStLoad();
		updateStLoadUndoState();
		StockLoadingAlert.dismiss();
		if (DISPLAYSUMMARY == 202) {
			Intent myIntent = new Intent(this, DM_Stock_UnLoading.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			DELTAG = 0;
			finish();
			return;
		}
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		// CLEARTAG = 22;
		clearFieldsStLoad();
		updateStLoadUndoState();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		StockLoadingAlert.dismiss();
		finish();
		return;
	}

	private void updateStLoadUndoState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String columsup[] = { "stlrepusername", "stLoadActive" };
		Cursor undoStockLoadingMain = null;
		try {
			undoStockLoadingMain = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN,
					null, "stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (undoStockLoadingMain != null) {
			if (undoStockLoadingMain.getCount() > 0) {
				while (undoStockLoadingMain.moveToNext()) {
					ContentValues valueupdateStLoadState = new ContentValues();
					stLoadCurrentid = undoStockLoadingMain.getString(0);
					tempRepUnStLoadSerialCode = undoStockLoadingMain
							.getString(5);
					valueupdateStLoadState.put("stLoadActive", "9");
					valueupdateStLoadState.put("stLoadComplete", "0");
					valueupdateStLoadState.put("stLoadActiveValue", "0");
					valueupdateStLoadState.put("stLoadstartDate",
							getCurrentTimeString());
					valueupdateStLoadState.put("fromLocName", "");
					valueupdateStLoadState.put("toLocName", "");

					mydb.update(TEMP_STOCK_LOADING_SUMMARYUN,
							valueupdateStLoadState, "temprepStLoad_id ='"
									+ stLoadCurrentid + "'", null);
				}

			}

		}
		undoStockLoadingMain.close();
		mydb.close();
		deleteStockLoadingItems();
	}

	private void deleteStockLoadingItems() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStLoadingItemDel = null;
		try {
			saveStLoadingItemDel = mydb.query(STOCK_LOAD_DETAILUN, null,
					"RefNo='" + tempRepUnStLoadSerialCode + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		if (saveStLoadingItemDel != null) {
			if (saveStLoadingItemDel.getCount() > 0) {
				while (saveStLoadingItemDel.moveToNext()) {
					String tempRepStLoadrefcode = saveStLoadingItemDel
							.getString(1);
					mydb.delete(STOCK_LOAD_DETAILUN, "RefNo ='"
							+ tempRepStLoadrefcode + "'", null);
				}
			}
		}

		Cursor saveStLoadinghedDel = null;
		try {
			saveStLoadinghedDel = mydb.query(STOCK_LOAD_HEADUN, null, "RefNo='"
					+ tempRepUnStLoadSerialCode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (saveStLoadinghedDel != null) {
			if (saveStLoadinghedDel.getCount() > 0) {
				while (saveStLoadinghedDel.moveToNext()) {
					String tempRepStLoadrefcode = saveStLoadinghedDel
							.getString(1);
					mydb.delete(STOCK_LOAD_HEADUN, "RefNo ='"
							+ tempRepStLoadrefcode + "'", null);
				}
			}
		}

		populateStockLoadList();
		saveStLoadinghedDel.close();
		saveStLoadingItemDel.close();
		mydb.close();
	}

	// =================================================================
	public void btnPrintStloading(View view) {
		if (etdmstloadingrefno.length() != 0) {
			checkStockLoadSaved();
			if (SAVEDTAG == 66) {
				String currentPrintRefNo = etdmstloadingrefno.getText()
						.toString();
				Intent myIntent = new Intent(view.getContext(),
						DM_Print_StockUnLoading.class);
				myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			} else {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Stock_UnLoading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("SAVE STOCK UNLOADING");
				// Setting Dialog Message
				alertDialog.setMessage("Selected Stock Unloading Not Saved.");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}
	}

	// Undo Invoice Handling
	public void btnPrintInvoiceCancel(View view) {
		StockLoadingAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		StockLoadingAlert.dismiss();
	}

	// Mainclass
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_stock_unloading);
		dbHelper = new DM_ItemsList_Adapter(this);
		dbHelper.open();
		// Handling layout controls
		account_saveButton = (Button) findViewById(R.id.account_saveButton);
		etdmstloadingrefno = (Button) findViewById(R.id.etdmstloadingrefno);
		etdmstloadingmanuno = (EditText) findViewById(R.id.etdmstloadingmanuno);
		etdmstloadingdate = (EditText) findViewById(R.id.etdmstloadingdate);
		etstockloadingFLoc = (EditText) findViewById(R.id.etstockloadingFLoc);
		etstockloadingToLoc = (EditText) findViewById(R.id.etstockloadingToLoc);
		etdmstloadingremark = (EditText) findViewById(R.id.etdmstloadingremark);
		etdmstloadingitemname = (EditText) findViewById(R.id.etdmstloadingitemname);
		etdmstloadingunits = (EditText) findViewById(R.id.etdmstloadingunits);
		etdmstloadingitemqoh = (EditText) findViewById(R.id.etdmstloadingitemqoh);
		etdmstloadingitemcases = (EditText) findViewById(R.id.etdmstloadingitemcases);
		etdmstloadingitemcases.addTextChangedListener(filtermaxcasesWatcher);
		etdmstloadingitempieces = (EditText) findViewById(R.id.etdmstloadingitempieces);
		etdmstloadingitempieces.addTextChangedListener(filtermaxpiecesWatcher);
		etdmstloadingitemprice = (EditText) findViewById(R.id.etdmstloadingitemprice);
		etdmstloadingcaseprice = (EditText) findViewById(R.id.etdmstloadingcaseprice);
		myFilterItems = (EditText) findViewById(R.id.dminvfilteritems);
		// Main layout display
		dmstloadStockLoadingList = (LinearLayout) findViewById(R.id.dmstloadStockLoadingList);
		ListViewStLoadShowLocations = (LinearLayout) findViewById(R.id.dmstloadLocationList);
		ListViewStLoadShowItems = (LinearLayout) findViewById(R.id.dmstloadItemsList);
		ListViewStockLoadDetails = (LinearLayout) findViewById(R.id.dmstloadmaindetails);
		StockLoadActionButtons = (LinearLayout) findViewById(R.id.dmstloadActionButtons);
		// Button controllers
		btnStockFromLocation = (Button) findViewById(R.id.btnStockFromLocation);
		btnStockToLocation = (Button) findViewById(R.id.btnStockToLocation);
		btdmstLoadingselectitem = (Button) findViewById(R.id.btdmstLoadingselectitem);
		// dmstockloadingback = (Button) findViewById(R.id.dmstockloadingback);
		dmstockloadingadd = (Button) findViewById(R.id.dmstockloadingadd);
		dmstockloadingupdate = (Button) findViewById(R.id.dmstockloadingupdate);
		dmstockloadingdelete = (Button) findViewById(R.id.dmstockloadingdelete);
		// Main loading functions
		currentUserStLoadChk();// Check Current User
		stLoadingAgentPrefix();// Check Current Agent Prefix
		stLoadingTransType();// Check Current Trans Type
		// checkCurrentStockLoading();// Check Current Stock Loading
		checkLatestStockUnoadingSerial();// Check Current Stock Loading
		populateStockLoadLocationList();// Stock Load Location List
		// populateStockLoadItemsList();// Stock Load Items List
		populateItemsDetailsList();
		deviceName();

		etdmstloadingrefno.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {
				int action = motionevent.getAction();
				if (action == MotionEvent.ACTION_DOWN) {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Button ACTION_DOWN", Toast.LENGTH_SHORT).show();
					 */
				} else if (action == MotionEvent.ACTION_UP) {
					dmstloadStockLoadingList.setVisibility(view.VISIBLE);
					ListViewStLoadShowLocations.setVisibility(view.GONE);
					ListViewStLoadShowItems.setVisibility(view.GONE);
					ListViewStockLoadDetails.setVisibility(view.GONE);
					StockLoadActionButtons.setVisibility(view.GONE);
					populateStockLoadingList();
					// jana
				}
				return false;

			}

		});

		// List Stock Loading Location
		btnStockFromLocation.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				LocationTag = 100;
				populateStockLoadLocationList();
				ListViewStLoadShowLocations.setVisibility(view.VISIBLE);
				ListViewStLoadShowItems.setVisibility(view.GONE);
				ListViewStockLoadDetails.setVisibility(view.GONE);
				StockLoadActionButtons.setVisibility(view.GONE);
			}

		});
		// List Stock Loading Location
		btnStockToLocation.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				LocationTag = 200;
				populateStockLoadLocationList();
				ListViewStLoadShowLocations.setVisibility(view.VISIBLE);
				ListViewStLoadShowItems.setVisibility(view.GONE);
				ListViewStockLoadDetails.setVisibility(view.GONE);
				StockLoadActionButtons.setVisibility(view.GONE);
			}

		});
		// List available items with the stock
		btdmstLoadingselectitem.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// myFilterItems.setText("");
				// myFilterItems.clearFocus();
				// myFilterItems.requestFocus();
				if (etstockloadingFLoc.length() != 0
						&& etstockloadingToLoc.length() != 0) {
					ListViewStLoadShowItems.setVisibility(view.VISIBLE);
					ListViewStLoadShowLocations.setVisibility(view.GONE);
					ListViewStockLoadDetails.setVisibility(view.GONE);
					StockLoadActionButtons.setVisibility(view.GONE);
				} else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("INVALID LOCATIONS");
					// Setting Dialog Message
					alertDialog.setMessage("Please Select Locations First..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}

			}

		});

		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		// Save StockLoading Details in to stLoadHead & stLoadDetails
		dmstockloadingadd.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (etstockloadingFLoc.length() == 0
						|| etstockloadingToLoc.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT LOCATIONS");
					// Setting Dialog Message
					alertDialog.setMessage("Select Item Locations...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else if (etdmstloadingitemname.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT ITEM");
					// Setting Dialog Message
					alertDialog.setMessage("Select An Item...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else if (etdmstloadingitemcases.length() == 0
						&& etdmstloadingitempieces.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT ITEM QTY");
					// Setting Dialog Message
					alertDialog.setMessage("Select Unloading Item Quantity...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else if (etdmstloadingitemqoh.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Stock_UnLoading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("NO AVAILABLE STOCK");
					// Setting Dialog Message
					alertDialog
							.setMessage("Stock Not Found From the Location.Select New Item..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else {
					double CasesQtyVal = 0.00;
					double PiecesQtyVal = 0.00;
					if (etdmstloadingitemcases.length() != 0) {
						String chkCasesQtyStr = etdmstloadingitemcases
								.getText().toString();
						CasesQtyVal = Double.parseDouble(chkCasesQtyStr
								.replaceAll("[,]", ""));
					}
					if (etdmstloadingitempieces.length() != 0) {
						String chkPiecesQtyStr = etdmstloadingitempieces
								.getText().toString();
						PiecesQtyVal = Double.parseDouble(chkPiecesQtyStr
								.replaceAll("[,]", ""));
					}

					if (CasesQtyVal > 0 || PiecesQtyVal > 0) {
						saveStockLoadingDetails();
					} else {
						chkCasePiecesQuantity();
					}
				}
			}

			// SA
			private void saveStockLoadingDetails() {
				// TODO Auto-generated method stub
				SAVETAG = 55;
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				// Check last sequence
				SelectSequence();
				// Total value calculation
				try {
					// case price
					String stl_case_price = etdmstloadingcaseprice.getText()
							.toString();
					Double stl_case_price_val = Double
							.parseDouble(stl_case_price);
					// item price
					String stl_item_price = etdmstloadingitemprice.getText()
							.toString();
					Double stl_item_price_val = Double
							.parseDouble(stl_item_price);
					// item init QTY
					String stl_item_unit_qty = etdmstloadingunits.getText()
							.toString();
					Double stl_item_unit_qty_val = Double
							.parseDouble(stl_item_unit_qty);

					// TotStLoadCaseItems=0.0,TotStLoadPieces=0.0;
					if (etdmstloadingitemcases.length() != 0) {
						String Loading_case_qty = etdmstloadingitemcases
								.getText().toString();
						Double Stl_case_qty = Double
								.parseDouble(Loading_case_qty);
						case_price = Stl_case_qty * stl_case_price_val;
						TotStLoadCaseItems = Stl_case_qty
								* stl_item_unit_qty_val;
					}
					if (etdmstloadingitempieces.length() != 0) {
						String Loading_piece_qty = etdmstloadingitempieces
								.getText().toString();
						Double Stl_piece_qty = Double
								.parseDouble(Loading_piece_qty);
						piece_price = Stl_piece_qty * stl_item_price_val;
						TotStLoadPieces = Stl_piece_qty;
					}
					TotalLoadingValue = case_price + piece_price;
					TotalLoadingValue = Math.round(TotalLoadingValue * 100) / 100.0d;
					TotPiecesStLoad = TotStLoadCaseItems + TotStLoadPieces;

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				String CurrentSTLRefNo = etdmstloadingrefno.getText()
						.toString();
				Cursor saveStLoadinghedCur = null;
				try {
					saveStLoadinghedCur = mydb.query(STOCK_LOAD_HEADUN, null,
							"RefNo='" + CurrentSTLRefNo + "'", null, null,
							null, null);
				} catch (Exception e) {
				}

				if (saveStLoadinghedCur != null) {
					if (saveStLoadinghedCur.getCount() > 0) {
						while (saveStLoadinghedCur.moveToNext()) {
							String CurrentRefID = saveStLoadinghedCur
									.getString(0);
							String CurrentTotalValue = saveStLoadinghedCur
									.getString(7);
							Double stl_CurrentTotalValue = Double
									.parseDouble(CurrentTotalValue);
							Double New_Cur_TotalValue = stl_CurrentTotalValue
									+ TotalLoadingValue;
							String PrintTotalLoadingValue = Double
									.toString(New_Cur_TotalValue);

							ContentValues valueupdateStlHead = new ContentValues();
							valueupdateStlHead.put("TotalAmt",
									PrintTotalLoadingValue);
							mydb.update(STOCK_LOAD_HEADUN, valueupdateStlHead,
									"RecordId=" + CurrentRefID, null);
						}
					} else {
						// Save Invoice header details
						try {
							ContentValues newStockLoadRec = new ContentValues();
							String PrintTotalLoadingValue = Double
									.toString(TotalLoadingValue);
							newStockLoadRec.put("RefNo", etdmstloadingrefno
									.getText().toString());
							newStockLoadRec.put("TxnDate", etdmstloadingdate
									.getText().toString());
							newStockLoadRec.put("ManuRef", etdmstloadingmanuno
									.getText().toString());
							newStockLoadRec.put("CostCode", "");
							newStockLoadRec.put("Remarks", etdmstloadingremark
									.getText().toString());
							newStockLoadRec.put("TxnType", "43");
							newStockLoadRec.put("TotalAmt",
									PrintTotalLoadingValue);
							newStockLoadRec.put("DelPersn", "");
							newStockLoadRec.put("DelAdd1", "");
							newStockLoadRec.put("DelAdd2", "");
							newStockLoadRec.put("DelAdd3", "");
							newStockLoadRec.put("VehicalNo", "");
							newStockLoadRec.put("GlPost", "");
							newStockLoadRec.put("GlBatch", "");
							newStockLoadRec.put("AddUser", currentUserStLoad);
							newStockLoadRec.put("AddDatestlh",
									getAddDateTimeString().toString());
							newStockLoadRec.put("AddMach", deviceUser);
							newStockLoadRec.put("TranFlg", "0");
							newStockLoadRec.put("ItemType", "0");
							newStockLoadRec.put("stlhedunSync", "0");
							newStockLoadRec.put("IntangFlg", "0");

							mydb.insert(STOCK_LOAD_HEADUN, null,
									newStockLoadRec);

						} catch (Exception e) {
							Toast.makeText(getApplicationContext(),
									"Error Occured..", Toast.LENGTH_SHORT)
									.show();
						}
					}
				}

				// Save Invoice Details
				try {
					// Calculate currentLocationItemQty
					Cursor chkcurrentLocQty = null;
					try {
						chkcurrentLocQty = mydb.query(ITEM_LOC_DETAILS, null,
								"ItemCode='" + stLoaditemcode
										+ "' AND LocCode='"
										+ currentToLocationCode + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (chkcurrentLocQty != null) {
						if (chkcurrentLocQty.getCount() > 0) {
							while (chkcurrentLocQty.moveToNext()) {
								currentToLocQty = chkcurrentLocQty.getString(3);
								// currentToLocQty =
								// Double.parseDouble(currentQty);
							}
						}
					}

					// Pre Calculations for cases Pieces
					String casePieces = etdmstloadingunits.getText().toString();
					casePieQtyValue = Integer.parseInt(casePieces);

					if (etdmstloadingitemcases.length() != 0) {
						String caseQtyStr = etdmstloadingitemcases.getText()
								.toString();
						caseQtyValue = Integer.parseInt(caseQtyStr);
					}
					if (etdmstloadingitempieces.length() != 0) {
						String piecesQtyStr = etdmstloadingitempieces.getText()
								.toString();
						casePiecesValue = Integer.parseInt(piecesQtyStr);
					}
					if (casePiecesValue >= casePieQtyValue) {
						Integer newCasesQty = casePiecesValue / casePieQtyValue;
						caseQtyValue = caseQtyValue + newCasesQty;

						casePiecesValue = (casePiecesValue - (newCasesQty * casePieQtyValue));
					}

					//

					ContentValues newStockLoadRecDetail = new ContentValues();
					newStockLoadRecDetail.put("RefNo", etdmstloadingrefno
							.getText().toString());
					newStockLoadRecDetail.put("TxnDate", etdmstloadingdate
							.getText().toString());

					if (currentToLocationCode.length() != 0) {
						newStockLoadRecDetail.put("LocCode",
								currentToLocationCode);
					} else {
						newStockLoadRecDetail.put("LocCode", "LV001");
					}
					newStockLoadRecDetail.put("TxnType", "43");
					newStockLoadRecDetail.put("SeqNo", stLoadLastSequence);
					newStockLoadRecDetail.put("ItemCode", stLoaditemcode);

					String PrintcaseQtyValue = Integer.toString(caseQtyValue);
					newStockLoadRecDetail.put("CaseQty", PrintcaseQtyValue);

					String PrintcasePiecesValue = Integer
							.toString(casePiecesValue);
					newStockLoadRecDetail.put("PiceQty", PrintcasePiecesValue);

					newStockLoadRecDetail.put("Qty", TotPiecesStLoad);
					newStockLoadRecDetail.put("CostPrice",
							PrintcurrentUnitPriceAverage);
					newStockLoadRecDetail.put("Amt", TotalLoadingValue);
					newStockLoadRecDetail.put("RecordDate",
							getCurrentTimeString().toString());
					newStockLoadRecDetail.put("RecordChecked", "99");
					newStockLoadRecDetail.put("LitemName",
							etdmstloadingitemname.getText().toString());
					newStockLoadRecDetail.put("LitemQOH", currentToLocQty);
					newStockLoadRecDetail.put("CaseUnits", etdmstloadingunits
							.getText().toString());
					newStockLoadRecDetail.put("stldetunSync", "0");
					newStockLoadRecDetail.put("IntangFlg", "0");
					mydb.insert(STOCK_LOAD_DETAILUN, null,
							newStockLoadRecDetail);
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}
				// Save Invoice Details *-1
				try {
					ContentValues newStockLoadRecDetail = new ContentValues();
					newStockLoadRecDetail.put("RefNo", etdmstloadingrefno
							.getText().toString());
					newStockLoadRecDetail.put("TxnDate", etdmstloadingdate
							.getText().toString());
					newStockLoadRecDetail.put("LocCode",
							currentFromLocationCode);
					newStockLoadRecDetail.put("TxnType", "43");
					newStockLoadRecDetail.put("SeqNo", stLoadLastSequence);
					newStockLoadRecDetail.put("ItemCode", stLoaditemcode);

					String PrintcaseQtyValue = Integer.toString(caseQtyValue);
					newStockLoadRecDetail.put("CaseQty", PrintcaseQtyValue);

					String PrintcasePiecesValue = Integer
							.toString(casePiecesValue);
					newStockLoadRecDetail.put("PiceQty", PrintcasePiecesValue);

					newStockLoadRecDetail.put("Qty", TotPiecesStLoad * -1);
					newStockLoadRecDetail.put("CostPrice",
							PrintcurrentUnitPriceAverage);
					newStockLoadRecDetail.put("Amt", TotalLoadingValue * -1);
					newStockLoadRecDetail.put("RecordDate",
							getCurrentTimeString().toString());
					newStockLoadRecDetail.put("RecordChecked", "88");
					newStockLoadRecDetail.put("LitemName",
							etdmstloadingitemname.getText().toString());
					newStockLoadRecDetail.put("LitemQOH", etdmstloadingitemqoh
							.getText().toString());
					newStockLoadRecDetail.put("CaseUnits", etdmstloadingunits
							.getText().toString());
					newStockLoadRecDetail.put("stldetunSync", "0");
					newStockLoadRecDetail.put("IntangFlg", "0");
					mydb.insert(STOCK_LOAD_DETAILUN, null,
							newStockLoadRecDetail);
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				// Calling After saving one record in to Stock Loading Tables
				btnStockFromLocation.setEnabled(false);
				btnStockToLocation.setEnabled(false);
				resetCalculation();
				populateStockLoadList();
				mydb.close();
			}

		});
		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		dmstockloadingupdate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				double CasesQtyVal = 0.00;
				double PiecesQtyVal = 0.00;
				if (etdmstloadingitemcases.length() != 0) {
					String chkCasesQtyStr = etdmstloadingitemcases.getText()
							.toString();
					CasesQtyVal = Double.parseDouble(chkCasesQtyStr.replaceAll(
							"[,]", ""));
				}
				if (etdmstloadingitempieces.length() != 0) {
					String chkPiecesQtyStr = etdmstloadingitempieces.getText()
							.toString();
					PiecesQtyVal = Double.parseDouble(chkPiecesQtyStr
							.replaceAll("[,]", ""));
				}

				if (CasesQtyVal > 0 || PiecesQtyVal > 0) {
					updateStockLoadingRecord();
				} else {
					chkCasePiecesQuantity();
				}

			}

			private void updateStockLoadingRecord() {
				// TODO Auto-generated method stub
				// Total value calculation
				try {
					// case price
					String stl_case_price = etdmstloadingcaseprice.getText()
							.toString();
					Double stl_case_price_val = Double
							.parseDouble(stl_case_price);
					// item price
					String stl_item_price = etdmstloadingitemprice.getText()
							.toString();
					Double stl_item_price_val = Double
							.parseDouble(stl_item_price);
					// item init QTY
					String stl_item_unit_qty = etdmstloadingunits.getText()
							.toString();
					Double stl_item_unit_qty_val = Double
							.parseDouble(stl_item_unit_qty);

					// TotStLoadCaseItems=0.0,TotStLoadPieces=0.0;
					if (etdmstloadingitemcases.length() != 0) {
						String Loading_case_qty = etdmstloadingitemcases
								.getText().toString();
						Double Stl_case_qty = Double
								.parseDouble(Loading_case_qty);
						case_price = Stl_case_qty * stl_case_price_val;
						TotStLoadCaseItems = Stl_case_qty
								* stl_item_unit_qty_val;
					}
					if (etdmstloadingitempieces.length() != 0) {
						String Loading_piece_qty = etdmstloadingitempieces
								.getText().toString();
						Double Stl_piece_qty = Double
								.parseDouble(Loading_piece_qty);
						piece_price = Stl_piece_qty * stl_item_price_val;
						TotStLoadPieces = Stl_piece_qty;
					}
					TotalLoadingValue = case_price + piece_price;
					TotPiecesStLoad = TotStLoadCaseItems + TotStLoadPieces;

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

				// Pre Calculations for cases Pieces
				String casePieces = etdmstloadingunits.getText().toString();
				casePieQtyValue = Integer.parseInt(casePieces);

				if (etdmstloadingitemcases.length() != 0) {
					String caseQtyStr = etdmstloadingitemcases.getText()
							.toString();
					caseQtyValue = Integer.parseInt(caseQtyStr);
				}
				if (etdmstloadingitempieces.length() != 0) {
					String piecesQtyStr = etdmstloadingitempieces.getText()
							.toString();
					casePiecesValue = Integer.parseInt(piecesQtyStr);
				}
				if (casePiecesValue >= casePieQtyValue) {
					Integer newCasesQty = casePiecesValue / casePieQtyValue;
					caseQtyValue = caseQtyValue + newCasesQty;

					casePiecesValue = (casePiecesValue - (newCasesQty * casePieQtyValue));
				}
				// Updating Invoice Details
				try {
					ContentValues newStockLoadRecDetailUpdateP = new ContentValues();
					newStockLoadRecDetailUpdateP
							.put("ItemCode", stLoaditemcode);

					String PrintcaseQtyValue = Integer.toString(caseQtyValue);
					newStockLoadRecDetailUpdateP.put("CaseQty",
							PrintcaseQtyValue);

					String PrintcasePiecesValue = Integer
							.toString(casePiecesValue);
					newStockLoadRecDetailUpdateP.put("PiceQty",
							PrintcasePiecesValue);

					/*
					 * newStockLoadRecDetailUpdateP.put("CaseQty",
					 * etdmstloadingitemcases.getText().toString());
					 * newStockLoadRecDetailUpdateP.put("PiceQty",
					 * etdmstloadingitempieces.getText().toString());
					 */
					newStockLoadRecDetailUpdateP.put("Qty", TotPiecesStLoad);
					newStockLoadRecDetailUpdateP.put("CostPrice",
							PrintcurrentUnitPriceAverage);
					newStockLoadRecDetailUpdateP.put("Amt", TotalLoadingValue);
					newStockLoadRecDetailUpdateP.put("RecordDate",
							getCurrentTimeString().toString());
					newStockLoadRecDetailUpdateP.put("RecordChecked", "99");
					newStockLoadRecDetailUpdateP.put("LitemName",
							etdmstloadingitemname.getText().toString());
					newStockLoadRecDetailUpdateP.put("LitemQOH",
							etdmstloadingitemqoh.getText().toString());
					newStockLoadRecDetailUpdateP.put("CaseUnits",
							etdmstloadingunits.getText().toString());
					mydb.update(STOCK_LOAD_DETAILUN,
							newStockLoadRecDetailUpdateP, "RecordId="
									+ LocationItemLoadRecId, null);
					// /mydb.update(STOCK_LOAD_DETAIL, null,
					// newStockLoadRecDetail);
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				// Updating Invoice Details Negative
				try {
					ContentValues newStockLoadRecDetailUpdateN = new ContentValues();
					newStockLoadRecDetailUpdateN
							.put("ItemCode", stLoaditemcode);

					String PrintcaseQtyValue = Integer.toString(caseQtyValue);
					newStockLoadRecDetailUpdateN.put("CaseQty",
							PrintcaseQtyValue);

					String PrintcasePiecesValue = Integer
							.toString(casePiecesValue);
					newStockLoadRecDetailUpdateN.put("PiceQty",
							PrintcasePiecesValue);

					/*
					 * newStockLoadRecDetailUpdateN.put("CaseQty",
					 * etdmstloadingitemcases.getText().toString());
					 * newStockLoadRecDetailUpdateN.put("PiceQty",
					 * etdmstloadingitempieces.getText().toString());
					 */
					newStockLoadRecDetailUpdateN.put("Qty", TotPiecesStLoad
							* -1);
					newStockLoadRecDetailUpdateN.put("CostPrice",
							PrintcurrentUnitPriceAverage);
					newStockLoadRecDetailUpdateN.put("Amt", TotalLoadingValue
							* -1);
					newStockLoadRecDetailUpdateN.put("RecordDate",
							getCurrentTimeString().toString());
					newStockLoadRecDetailUpdateN.put("RecordChecked", "88");
					newStockLoadRecDetailUpdateN.put("LitemName",
							etdmstloadingitemname.getText().toString());
					newStockLoadRecDetailUpdateN.put("LitemQOH",
							etdmstloadingitemqoh.getText().toString());
					newStockLoadRecDetailUpdateN.put("CaseUnits",
							etdmstloadingunits.getText().toString());
					int negItemupdating = LocationItemLoadRecId + 1;
					mydb.update(STOCK_LOAD_DETAILUN,
							newStockLoadRecDetailUpdateN, "RecordId="
									+ negItemupdating, null);
					// /mydb.update(STOCK_LOAD_DETAIL, null,
					// newStockLoadRecDetail);
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}
				// Calling After saving one record in to Stock Loading Tables
				btnStockFromLocation.setEnabled(false);
				btnStockToLocation.setEnabled(false);
				resetCalculation();
				clearFieldsStLoad();
				populateStockLoadList();

				mydb.close();
			}
		});

		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		// Delete Stock Load Item From List
		dmstockloadingdelete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				DELTAG = 88;
				// item init QTY
				String stl_item_unit_qty = etdmstloadingunits.getText()
						.toString();
				Double stl_item_unit_qty_val = Double
						.parseDouble(stl_item_unit_qty);
				if (etdmstloadingitemcases.length() != 0) {
					String Loading_case_qty = etdmstloadingitemcases.getText()
							.toString();
					Double Stl_case_qty = Double.parseDouble(Loading_case_qty);
					TotStLoadCaseItems = Stl_case_qty * stl_item_unit_qty_val;
				}
				if (etdmstloadingitempieces.length() != 0) {
					String Loading_piece_qty = etdmstloadingitempieces
							.getText().toString();
					Double Stl_piece_qty = Double
							.parseDouble(Loading_piece_qty);
					TotStLoadPieces = Stl_piece_qty;
				}
				TotPiecesStLoad = TotStLoadCaseItems + TotStLoadPieces;

				int negItemupdating = LocationItemLoadRecId + 1;
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectDelitem = null;
				Cursor selectHeditem = null;

				try {
					selectHeditem = mydb.query(STOCK_LOAD_HEADUN, null, null,
							null, null, null, null);
				} catch (Exception e) {
				}

				try {
					selectDelitem = mydb.query(STOCK_LOAD_DETAILUN, null, null,
							null, null, null, null);
				} catch (Exception e) {
				}

				try {

					if (selectHeditem != null) {
						if (selectHeditem.getCount() > 0) {
							while (selectHeditem.moveToNext()) {
								mydb.delete(STOCK_LOAD_HEADUN, "RecordId ='"
										+ LocationItemLoadRecId + "'", null);

							}

						}
					}

					if (selectDelitem != null) {
						if (selectDelitem.getCount() > 0) {
							while (selectDelitem.moveToNext()) {
								String TAG = null;
								mydb.delete(STOCK_LOAD_DETAILUN, "RecordId ='"
										+ LocationItemLoadRecId + "'", null);
								mydb.delete(STOCK_LOAD_DETAILUN, "RecordId ='"
										+ negItemupdating + "'", null);
								Log.v(TAG, "SLD 1:" + LocationItemLoadRecId);
							}
						}
					}

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				btnStockFromLocation.setEnabled(false);
				btnStockToLocation.setEnabled(false);
				selectDelitem.close();
				selectHeditem.close();
				mydb.close();

				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Stock_UnLoading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("DELETE ITEM");
				// Setting Dialog Message
				alertDialog.setMessage("Delete Item Success...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								/*
								 * currentFromLocationCode = "";
								 * currentToLocationCode = "";
								 */
								populateStockLoadList();
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
				// populateStockLoadList();
			}
		});
	}

	protected void chkCasePiecesQuantity() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_Stock_UnLoading.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("ENTER ITEM QTY");
		// Setting Dialog Message
		alertDialog
				.setMessage("Enter Cases / Pieces Quantities For Selected Item..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	private void populateStockLoadingList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewPreStLoadList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invListingViewNo,
				R.id.invListingViewSum };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			String query = "SELECT * fROM frepStockLoadingSummaryUn Where stLoadActive ='2'";
			allrowtypedes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String stloadRef = allrowtypedes.getString(5);

					String rawitemsdet = stloadRef;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawitemsdet);
					maptrdes.put("coldes_2", stloadRef);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_pre_stloading_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
				// DM_List_Expand_Helper.getListViewSize(lvtypedes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	private void deviceName() {
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	protected void resetCalculation() {
		// TODO Auto-generated method stub
		TotPiecesStLoad = 0.0;
		TotStLoadCaseItems = 0.0;
		TotStLoadPieces = 0.0;
		TotalLoadingValue = 0.0;
		case_price = 0.0;
		piece_price = 0.0;
	}

	// Get latest sequence number
	protected void SelectSequence() {

		// Check Previously item Enter or Not
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor chkItemSequence = null;

		String query = "SELECT RecordId from fUnLoadDet order by RecordId DESC limit 1";
		Cursor c = mydb.rawQuery(query, null);
		if (c != null && c.moveToLast()) {
			lastId = c.getLong(0);
			strlastId = Long.toString(lastId);
		}

		try {
			chkItemSequence = mydb.query(STOCK_LOAD_DETAILUN, null,
					"RecordId='" + strlastId + "'", null, null, null, null);
		} catch (Exception e1) {
		}

		try {
			if (chkItemSequence != null) {
				if (chkItemSequence.getCount() > 0) {
					while (chkItemSequence.moveToNext()) {
						String rawid = chkItemSequence.getString(0);
						LatestStLoadRefNo = chkItemSequence.getString(1);
						String strinvDetLastSequence = chkItemSequence
								.getString(5);
						stLoadLastSequence = Integer
								.parseInt(strinvDetLastSequence);
						if (LatestStLoadRefNo.equals(currentStLoadTempRefCode)) {
							stLoadLastSequence = stLoadLastSequence + 1;
						} else {
							stLoadLastSequence = 1;
						}
					}
				} else {
					stLoadLastSequence = 1;
				}
			} else {
				stLoadLastSequence = 1;
			}

		} catch (Exception e1) {
			Toast.makeText(getApplicationContext(), "Error Select Sequence..",
					Toast.LENGTH_SHORT).show();
		}
		chkItemSequence.close();
		mydb.close();

	}

	private void checkLatestStockUnoadingSerial() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectInvoiceSerial = null;

		try {
			selectInvoiceSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='STRUN' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}

		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN, null,
					"stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}

		if (selectInvoiceSerial != null) {
			if (selectInvoiceSerial.getCount() > 0) {
				while (selectInvoiceSerial.moveToNext()) {
					String cSettingsCode = selectInvoiceSerial.getString(3);
					String nNumVal = selectInvoiceSerial.getString(4);
					tempRepStLoadSerialStr = nNumVal.trim();
					if (selectLastinvrec != null) {
						if (selectLastinvrec.getCount() > 0) {
							if (selectLastinvrec.moveToLast()) {
								viewCurrentStockLoad();
							}
						} else if (selectLastinvrec.getCount() <= 0) {
							saveTempStoreLoading();// Save Store Loading
						}
					}

				}
			} else {
				tempRepStLoadSerialStr = "1";
				try {
					ContentValues newAdjustment = new ContentValues();
					newAdjustment.put("BranchCode", currentUserStLoad);
					newAdjustment.put("RecordId", "1");
					newAdjustment.put("cSettingsCode", "STRUN");
					newAdjustment.put("nNumVal", tempRepStLoadSerialStr);
					mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);
					saveTempStoreLoading();// Save Store Loading

				} catch (Exception e) {
					Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
							.show();
				}
				mydb.close();
			}
		}
		selectInvoiceSerial.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	protected void clearFieldsStLoad() {
		caseQtyValue = 0;
		casePiecesValue = 0;
		casePieQtyValue = 0;
		if (CLEARTAG == 22) {
			etstockloadingFLoc.setText("");
			etstockloadingToLoc.setText("");
		}
		// TODO Auto-generated method stub
		etdmstloadingmanuno.setText("");
		etdmstloadingdate.setText(getCurrentTimeString().toString());
		// etdmstloadingremark.setText("");
		etdmstloadingitemname.setText("");
		etdmstloadingunits.setText("");
		etdmstloadingitemqoh.setText("");
		etdmstloadingitemcases.setText("");
		etdmstloadingitempieces.setText("");
		dmstockloadingadd.setEnabled(true);
		dmstockloadingdelete.setEnabled(false);
		dmstockloadingupdate.setEnabled(false);

		// populateStockLoadList();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// populate Stock LoadList
	protected void populateStockLoadList() {
		// TODO Auto-generated method stub
		SimpleAdapter adaptertrdes = null;
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colstloaddes_1", "colstloaddes_2",
				"colstloaddes_3", "colstloaddes_4" };
		int[] totrdes = new int[] { R.id.stloaditemrefdet,
				R.id.stloadcasevalue, R.id.stloadpiecevalue,
				R.id.btnstloaditemrefdet };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };
		String col = "ItemCode";
		try {
			allrowitemsdes = mydb.query(STOCK_LOAD_DETAILUN, null, "RefNo='"
					+ currentStLoadTempRefCode + "' AND RecordChecked='99'",
					null, null, null, null);

		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String recid = allrowitemsdes.getString(0);
					listsequence = allrowitemsdes.getString(5);
					String ItemCode = allrowitemsdes.getString(6);
					String PiceQty = allrowitemsdes.getString(7);
					String CaseQty = allrowitemsdes.getString(8);
					String ItemName = allrowitemsdes.getString(14);
					String ItemQOH = allrowitemsdes.getString(15);
					String CaseUnits = allrowitemsdes.getString(16);
					checkLoadedListQoh();
					String rawitemsdet = recid + "/" + ItemCode + "/" + CaseQty
							+ "/" + PiceQty + "/" + ItemName + "/"
							+ ItemQOHFromLoc + "/" + CaseUnits;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colstloaddes_1", ItemName);
					maptrdes.put("colstloaddes_2", CaseQty);
					maptrdes.put("colstloaddes_3", PiceQty);
					maptrdes.put("colstloaddes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
						R.layout.dm_stock_loading_list_raw, fromtrdes, totrdes);

				lvtypedes.setAdapter(adaptertrdes);
			}
			int recRemCount = allrowitemsdes.getCount();
			if (recRemCount == 0 && DELTAG == 88) {
				Intent myIntent = new Intent(this, DM_Stock_UnLoading.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				DELTAG = 0;
				finish();
				return;
			} else if (recRemCount == 0 && CLEARTAG == 22) {
				Intent myIntent = new Intent(this, DM_Stock_UnLoading.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				CLEARTAG = 0;
				finish();
				return;
			}
		}
		clearFieldsStLoad();
		allrowitemsdes.close();
		mydb.close();
	}

	private void checkLoadedListQoh() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowcurrent = null;
		try {
			allrowcurrent = mydb.query(STOCK_LOAD_DETAILUN, null, "RefNo='"
					+ currentStLoadTempRefCode
					+ "' AND RecordChecked='88' AND SeqNo ='" + listsequence
					+ "'", null, null, null, null);

		} catch (Exception e) {
		}
		if (allrowcurrent != null) {
			if (allrowcurrent.getCount() > 0) {
				while (allrowcurrent.moveToNext()) {
					ItemQOHFromLoc = allrowcurrent.getString(15);
				}
			}
		}
		allrowcurrent.close();
		mydb.close();
	}

	@SuppressLint("NewApi")
	private void populateItemsDetailsList() {
		// TODO Auto-generated method stub
		Cursor cursor = dbHelper.fetchAllItems();

		// The desired columns to be bound
		String[] columns = new String[] { DM_ItemsList_Adapter.KEY_ITEMCODE,
				DM_ItemsList_Adapter.KEY_ITEMNAME };

		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.invoiceitemsdet, R.id.invitemsname, };

		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapter = new SimpleCursorAdapter(this,
				R.layout.dm_location_items_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listviewStLoadItemsList);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapter);

		myFilterItems.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapter.getFilter().filter(s.toString());
			}
		});

		dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			public Cursor runQuery(CharSequence constraint) {
				return dbHelper.fetchItemsByName(constraint.toString());
			}
		});
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Stock Load Items List
	private void populateStockLoadItemsList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewStLoadItemsList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoiceitemsdet, R.id.invitemsname };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(ITEMS, null, null, null, null, null,
					null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String itemskucode = allrowtypedes.getString(1);
					String itemcode = allrowtypedes.getString(2);
					String itemname = allrowtypedes.getString(4);
					String itemsincase = allrowtypedes.getString(28);

					String rawitemsdet = itemskucode + "/" + itemcode + "/"
							+ itemname + "/" + itemsincase;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawitemsdet);
					maptrdes.put("coldes_2", itemname);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_location_items_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Stock Load Location List
	private void populateStockLoadLocationList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewLocationList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invstloclocationname,
				R.id.invstloclocationdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(ITEM_LOCATION, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String LocCode = allrowtypedes.getString(9);
					String LocName = allrowtypedes.getString(10);
					String LoctCode = allrowtypedes.getString(11);

					if (LocationTag == 100 && LoctCode.trim().equals("LT3")
							&& LocCode.equals(currentUserLocation)) {
						String columnfLocdet = LocCode + "/" + LocName + "/"
								+ LoctCode;
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("coldes_1", LocCode + " - " + LocName);
						maptrdes.put("coldes_2", columnfLocdet);
						fillMapstrdes.add(maptrdes);
					} else if (LocationTag == 200
							&& !LoctCode.trim().equals("LT3")) {
						String columnfLocdet = LocCode + "/" + LocName + "/"
								+ LoctCode;
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("coldes_1", LocCode + " - " + LocName);
						maptrdes.put("coldes_2", columnfLocdet);
						fillMapstrdes.add(maptrdes);
					}
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_stock_locations_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {
					currentUserStLoad = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(5);
					currentUserServerDB = selectCurrentuserLoad.getString(7);
					UserAreaCode = selectCurrentuserLoad.getString(9);
					UserDealCode = selectCurrentuserLoad.getString(10);
					UserRouteCode = selectCurrentuserLoad.getString(11);

				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// Check Current Agent Prefix
	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
					stlAgentDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Trans Type
	private void stLoadingTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("STRUN")) {
						StlTransTypePrefix = cCharValue.trim();
					}
				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Stock Loading
	private void checkCurrentStockLoading() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN, null,
					"stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				if (selectLastinvrec.moveToLast()) {
					stlrepusername = selectLastinvrec.getString(1);
					tempRepStLoadSerialStr = selectLastinvrec.getString(4);
					String stLoadActive = selectLastinvrec.getString(7);
					int curtempRepStLoadSerial = Integer
							.parseInt(tempRepStLoadSerialStr);
					curtempRepStLoadSerial = curtempRepStLoadSerial + 1;
					tempRepStLoadSerialStr = Integer
							.toString(curtempRepStLoadSerial);
					viewCurrentStockLoad();

				}

			} else {
				int countRec = selectLastinvrec.getCount();
				if (countRec == 0) {
					tempRepStLoadSerialStr = "1";
					saveTempStoreLoading();// Save Store Loading
				}
			}
		} else {
			Toast.makeText(getApplicationContext(), "ActiveSerial CHK3",
					Toast.LENGTH_SHORT).show();
		}
		selectLastinvrec.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private void saveTempStoreLoading() {
		// TODO Auto-generated method stub
		RepStLoadCode = StlTransTypePrefix.trim() + stlAgentPrefixType.trim()
				+ currentUserPrefixLoad;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues saveStockLoadSummary = new ContentValues();
			saveStockLoadSummary.put("stlrepusername", currentUserStLoad);
			saveStockLoadSummary.put("stlrepprefix", currentUserPrefixLoad);
			saveStockLoadSummary.put("tempRepStLoadCode", RepStLoadCode);
			saveStockLoadSummary.put("tempRepStLoadSerial",
					tempRepStLoadSerialStr);

			try {
				if (tempRepStLoadSerialStr.length() == 1) {
					String newInvNumberStr = "00000" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 2) {
					String newInvNumberStr = "0000" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 3) {
					String newInvNumberStr = "000" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 4) {
					String newInvNumberStr = "00" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepStLoadSerialStr.length() == 5) {
					String newInvNumberStr = "0" + tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = tempRepStLoadSerialStr;
					currentStLoadTempRefCode = RepStLoadCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {

			}
			saveStockLoadSummary.put("tempRepStLoadRefNo",
					currentStLoadTempRefCode);
			saveStockLoadSummary.put("stLoadComplete", "0");
			saveStockLoadSummary.put("stLoadActive", "9");
			saveStockLoadSummary.put("stLoadActiveValue", "0");
			saveStockLoadSummary.put("stLoadstartDate", getCurrentTimeString());
			saveStockLoadSummary.put("fromLocName", "");
			saveStockLoadSummary.put("toLocName", "");
			mydb.insert(TEMP_STOCK_LOADING_SUMMARYUN, null,
					saveStockLoadSummary);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Record Not Insert..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();
		viewCurrentStockLoad();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	private void viewCurrentStockLoad() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor selectCurrentStockLoad = null;
		try {
			selectCurrentStockLoad = mydb.query(TEMP_STOCK_LOADING_SUMMARYUN,
					null, "stlrepusername='" + currentUserStLoad
							+ "' AND stLoadActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentStockLoad != null) {
			if (selectCurrentStockLoad.getCount() > 0) {
				if (selectCurrentStockLoad.moveToLast()) {
					currentStLoadTempRefCode = selectCurrentStockLoad
							.getString(5);
					String fromLocName = selectCurrentStockLoad.getString(10);
					String toLocName = selectCurrentStockLoad.getString(11);
					etdmstloadingrefno.setText(currentStLoadTempRefCode);
					etdmstloadingdate
							.setText(getCurrentTimeString().toString());

					if (fromLocName.length() > 0 && toLocName.length() > 0) {
						String[] fromLocNameArr = fromLocName.split("/");
						currentFromLocationCode = fromLocNameArr[0]; // location
																		// code
						fromLocName = fromLocNameArr[1]; // location Name
						String[] toLocNameArr = toLocName.split("/");
						currentToLocationCode = toLocNameArr[0];
						toLocName = toLocNameArr[1]; // location Name

						etstockloadingFLoc.setText(fromLocName);
						etstockloadingToLoc.setText(toLocName);
					}

					populateStockLoadList(); // List current invoice items
				}
			}
		}
		selectCurrentStockLoad.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private TextWatcher filtermaxpiecesWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			if (etdmstloadingitempieces.length() != 0) {
				if (etdmstloadingunits.length() != 0) {
					String CaseUnitAmount = etdmstloadingunits.getText()
							.toString();
					String CurrentPireces = etdmstloadingitempieces.getText()
							.toString();
					CaseUnitAmountVal = Double.parseDouble(CaseUnitAmount);
					CurrentPirecesVal = Double.parseDouble(CurrentPireces);
					/*
					 * if (CaseUnitAmountVal <= CurrentPirecesVal) {
					 * Toast.makeText(getApplicationContext(),
					 * "Maximum Items Pieces:" + CaseUnitAmount,
					 * Toast.LENGTH_SHORT).show();
					 * etdmstloadingitempieces.setText(""); }
					 */
				}

				if (etdmstloadingitemqoh.length() != 0) {
					String stockInHand = etdmstloadingitemqoh.getText()
							.toString();
					Double stockInHandVal = Double.parseDouble(stockInHand);
					Double TotPiecesInCase = 0.0;
					if (etdmstloadingitemcases.length() != 0) {
						String loadingCaseAmount = etdmstloadingitemcases
								.getText().toString();
						Double loadingCaseAmountVal = Double
								.parseDouble(loadingCaseAmount);
						TotPiecesInCase = loadingCaseAmountVal
								* CaseUnitAmountVal;
					}
					Double TotLoadingPieces = TotPiecesInCase
							+ CurrentPirecesVal;
					if (stockInHandVal < TotLoadingPieces) {
						Toast.makeText(
								getApplicationContext(),
								"Maximum Items Pieces On Hand:"
										+ stockInHandVal, Toast.LENGTH_SHORT)
								.show();
						etdmstloadingitempieces.setText("");
						etdmstloadingitemcases.setText("");
						CurrentPirecesVal = 0.0;
					}
				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}
	};

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private TextWatcher filtermaxcasesWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			if (etdmstloadingitemcases.length() != 0) {
				String stockInHand = etdmstloadingitemqoh.getText().toString();
				Double stockInHandVal = Double.parseDouble(stockInHand);

				String CaseUnitAmount = etdmstloadingunits.getText().toString();
				Double CaseUnitsVal = Double.parseDouble(CaseUnitAmount);

				if (etdmstloadingitempieces.length() != 0) {
					String CurrentPireces = etdmstloadingitempieces.getText()
							.toString();
					CurrentPirecesVal = Double.parseDouble(CurrentPireces);
				}

				String CurrentCases = etdmstloadingitemcases.getText()
						.toString();
				Double CurrentCasesVal = Double.parseDouble(CurrentCases);

				Double TotalLoadingPieces = (CaseUnitsVal * CurrentCasesVal)
						+ CurrentPirecesVal;

				if (stockInHandVal < TotalLoadingPieces) {
					Toast.makeText(getApplicationContext(),
							"Maximum Items Pieces On Hand:" + stockInHandVal,
							Toast.LENGTH_SHORT).show();
					etdmstloadingitempieces.setText("");
					etdmstloadingitemcases.setText("");
					CurrentPirecesVal = 0.0;
				}

			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}
	};

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// get current data and time
	private String getCurrentTimeStringCustom() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// **********Handling Dialog Box Functions*******************
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SAVE_STOCK_LOADING:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_saveprint_invoice, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Save Stock Unloading Success");
			dialogbuilder.setView(dialogview);
			StockLoadingAlert = dialogbuilder.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_CANCEL_STOCK_LOADING:
			LayoutInflater inflaterstl = LayoutInflater.from(this);
			View dialogviewstl = inflaterstl.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilderstl = new AlertDialog.Builder(this);
			dialogbuilderstl.setTitle("Cancel Stock Unloading...");
			dialogbuilderstl.setView(dialogviewstl);
			StockLoadingAlert = dialogbuilderstl.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_UNDO_STOCK_LOADING:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Stock Unloading...");
			dialogbuilderu.setView(dialogviewu);
			StockLoadingAlert = dialogbuilderu.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_PRINT_STOCK_LOADING:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			StockLoadingAlert = dialogbuilderp.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_PRINT_NON_PHYSICAL:
			LayoutInflater inflatern = LayoutInflater.from(this);
			View dialogviewn = inflatern.inflate(
					R.layout.dm_dialog_chk_nonphysical, null);

			AlertDialog.Builder dialogbuildern = new AlertDialog.Builder(this);
			dialogbuildern.setTitle("Non Physical Unloading ?");
			dialogbuildern.setView(dialogviewn);
			StockLoadingAlert = dialogbuildern.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		}

		return StockLoadingAlert;

	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
}
